﻿using Itech_Run.Helper.Sql;
using Itech_Run.Sys.Domain.Entity;
using Itech_Run.Sys.Domain.IRepository;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System.Dynamic;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace Itech_Run.Sys.EntityFrameworkCore.Repository
{
    public class Sys_RoleModuleButtonRepository : EfCoreRepository<Itech_RunSysContext, Sys_RoleModuleButton, string>, ISys_RoleModuleButtonRepository
    {
        private IDbContextProvider<Itech_RunSysContext> _dbContext;
        private IConfiguration _configuration;
        public Sys_RoleModuleButtonRepository(IDbContextProvider<Itech_RunSysContext> dbContextProvider, IConfiguration configuration) : base(dbContextProvider)
        {
            _dbContext = dbContextProvider;
            _configuration = configuration;
        }

        public List<dynamic> GetControllerButtonAuth(string userId)
        {
            string connectionString = _configuration.GetConnectionString("Itech_RunConnectionStr");
            var commandText = "SELECT DISTINCT m.ApiController,b.Code,rmb.HasAuth "+
"FROM Sys_RoleModuleButton rmb " +
"INNER JOIN dbo.Sys_Module m ON rmb.ModuleId = m.Id " +
"INNER JOIN dbo.Sys_Button b ON rmb.ButtonId = b.Id " +
"INNER JOIN dbo.Sys_UserRole ur ON rmb.RoleId=ur.RoleId " +
"WHERE ur.UserId=@userId AND rmb.HasAuth=1";
            var paras = new List<SqlParameter> { new SqlParameter("@userId", userId) };
            Func<SqlDataReader, List<dynamic>> dataReaderDelegate = executeDataReaderDelegate;
            return SqlHelper.GetDataReader(connectionString, commandText, paras, dataReaderDelegate);
        }

        private List<dynamic> executeDataReaderDelegate(SqlDataReader dataReader)
        {
            List<dynamic> results = new List<dynamic>();

            while (dataReader.Read())
            {
                dynamic dy = new ExpandoObject();
                dy.ApiController = dataReader[0];
                dy.Code = dataReader[1];
                dy.HasAuth = dataReader[2];
                results.Add(dy);
            }
            return results;
        }
    }
}
